import jsbeautifier
import time
import utils
import shutil
from bs4 import BeautifulSoup
import os



def extractJsFromHtml(inputfile, outputfile):
	content = open(inputfile, 'r').read()
	soup = BeautifulSoup(content)
	results = soup.find_all('script')	
	outputf = open(outputfile, 'w')
	if len(results) == 0:
		outputf.write(content)
		return
	for result in results:
		outputf.write(result.string)	


def extractJsFromHtmlDir(inputdir, outputdir):
	if not utils.checkdir(inputdir, outputdir):
		return
	infiles = utils.lsresult(inputdir)
	for infile in infiles:
		outfile = outputdir + '/' + infile
		infile = inputdir + infile
		if utils.checkfile(infile, outfile):
			extractJsFromHtml(infile, outfile)
	

def jsdeobfuscatefile(inputfile, outputfile):
	try:
		res = jsbeautifier.beautify_file(inputfile)
	except:
		res = open(inputfile, 'r').read()
	open(outputfile, 'w').write(res)


def jsdeobfuscatedir(inputdir, outputdir):
	if os.path.exists(outputdir):
		if os.path.isfile(outputdir):
			print 'The out dir is conflict with other filename'
			return
		shutil.rmtree(outputdir)
	os.makedirs(outputdir)
	# if not utils.checkdir(inputdir, outputdir):
	# 	return
	infiles = utils.lsresult(inputdir)
	for infile in infiles:
		outfile = outputdir + '/' + infile
		infile = inputdir + '/' + infile
		if utils.checkfile(infile, outfile):
			jsdeobfuscatefile(infile, outfile)
		

def deobJSTerry():
	inputdir = '../../data/JSTerry/javascript_20131018/'
	jsoutputdir = '../../data/JSTerry/javascript/'
	deoboutputdir = '../../data/JSTerry/deobjs/'
	extractJsFromHtmlDir(inputdir, jsoutputdir)
	jsdeobfuscatedir(jsoutputdir, deoboutputdir)


def main():
	inputdir = '../../data/TempData/JSFiles/'
	outputdir = '../../data/TempData/BeautifiedJS/'
	while True:
		jsdeobfuscatedir(inputdir, outputdir)
		print 'Sleeping'
		time.sleep(60 * 60 * 24)


if __name__=="__main__":
	# deobJSTerry()
	main()
	# extractJsFromHtml('../../data/JSTerry/javascript_20131018/i.hear-there.com_cececa7a856f2b6a796772e4af31dee6_19', 'temp')
